// src/utils/persistence.ts
import { ref, watch } from 'vue';

type PersistedStateOptions = {
  key: string;
  storage?: Storage;
  debounce?: number;
};

export const usePersistedRef = <T>(initialValue: T, options: PersistedStateOptions) => {
  const storage = options.storage || localStorage;
  const debounceTime = options.debounce || 500;

  // 从存储加载初始值
  const load = (): T => {
    try {
      const saved = storage.getItem(options.key);
      return saved ? JSON.parse(saved) : initialValue;
    } catch (e) {
      console.error('Failed to load persisted state:', e);
      return initialValue;
    }
  };

  // 创建响应式引用
  const state = ref<T>(load()) as Ref<T>;

  // 保存到存储
  const save = () => {
    try {
      storage.setItem(options.key, JSON.stringify(state.value));
    } catch (e) {
      console.error('Failed to save persisted state:', e);
    }
  };

  // 自动保存（带防抖）
  let saveTimeout: ReturnType<typeof setTimeout> | null = null;
  watch(
    state,
    () => {
      if (saveTimeout) {
        clearTimeout(saveTimeout);
      }
      saveTimeout = setTimeout(() => {
        save();
        saveTimeout = null;
      }, debounceTime);
    },
    { deep: true }
  );

  // 清除存储
  const clear = () => {
    storage.removeItem(options.key);
    state.value = initialValue;
  };

  return {
    state,
    save,
    clear
  };
};
